package com.cloudptt.api.comm;

import android.content.Context;
import android.os.Build;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;

import com.cloudptt.api.product.log.Log;
import com.mcptt.config.model.McIdInfo;

/**
 * @author SunnyCoffee
 * @date 2014-1-27
 * @version 1.0
 * @desc desc 公共常量
 *
 */
public class Common {

	private static final String THIS_FILE = "Common";
	public static final String LOCATION = "location";
	public static final String LOCATION_ACTION = "locationAction";

	public static String getDateAndTime() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format( new Date());
	}

	public static String getDateAndTime(long timeMillis) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date(timeMillis);
		return format.format( date);
	}

	public static String getTimeStr(long timeMillis) {
		SimpleDateFormat format = new SimpleDateFormat("HH:mm");
		Date date = new Date(timeMillis);
		return format.format( date);
	}

	public static String getDateAndTimeStr() {
		Date currentDate = new Date();
		// 格式化时间
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
		String format = dateFormat.format(currentDate);
		return format;
	}


	public static String getDateMillSeconds() {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSS");
		return format.format( new Date());
	}

	public static String getDateAndTime_s() {
		SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");

		String str =format.format( new Date());
		Log.debug(Common.class,"getDateAndTime_s str =  " + str + "len = " + str.length());
		return str;
	}

	public static String getDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format( new Date());
	}

	public static int getStrCount(String str) {
		try {
			if(str != null)
			{
				return str.getBytes("UTF-8").length;
			}
			return 0;
		}catch (Exception e)
		{
			e.printStackTrace();
			return 0;
		}
	}
	public static String substringByBytes(String str, int maxBytes){
		if (str == null || str.isEmpty()) return "";

		try {
			byte[] bytes = str.getBytes("UTF-8");
			if (bytes.length <= maxBytes) return str;

			// 避免截断多字节字符
			int n = maxBytes;
			while (n > 0 && (bytes[n] & 0xC0) == 0x80) n--;

			return new String(bytes, 0, n, "UTF-8");
		}catch (Exception e)
		{
			e.printStackTrace();
		}
		return new String("");
	}
	public static String substringUTF8(String str, int maxLength) {
		if (str == null || str.isEmpty()) {
			return str;
		}

		// 使用codePoint处理多字节字符
		int length = 0;
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < str.length(); ) {
			int codePoint = str.codePointAt(i);
			int charCount = Character.charCount(codePoint);

			if (length + charCount > maxLength) {
				break;
			}

			sb.appendCodePoint(codePoint);
			length += charCount;
			i += charCount;
		}

		return sb.toString();
	}



	// 生成n个全角空格的工具方法
	public static String generateSpaces(int n) {
		Log.debug(Common.class,"generateSpaces n =  " + n);
		if(n <=0)
		{
			n= 1;
		}
		if(n >20)
		{
			n = 20;
		}
		Log.debug(Common.class,"generateSpaces 1 n =  " + n);
		char[] temp = new char[n];
		Log.debug(Common.class,"generateSpaces temp =  " + temp);
		String str = new String(temp);
		Log.debug(Common.class,"generateSpaces str =  " + str);
		str = str.replace("\0", "　");
		Log.debug(Common.class,"generateSpaces str =  " + str);
		return str; // 全角空格
	}

//	public static long getDateSecs()
//	{
//		long currentTimeMillis = System.currentTimeMillis();
//		// 将毫秒数转换为秒数
//		return currentTimeMillis / 1000;
//	}

	public static long currentTimeMillis()
	{
		long currentTimeMillis = System.currentTimeMillis();
		Date date = new Date(currentTimeMillis);
		// 将毫秒数转换为秒数
		return date.getTime();
	}

//	public static long currentTimeSeconds()
//	{
//		long currentTimeMillis = System.currentTimeMillis();
//		// 将毫秒数转换为秒数
//		return currentTimeMillis / 1000;
//	}

	public static String getRandomString() {
		StringBuffer strBuf = new StringBuffer("abc");
		for(int i = 0; i < 5; i++)
		{
			Random ran = new Random();
			int a = ran.nextInt(99999999);
			String str = String.valueOf(a);
			strBuf.append(str);
		}
		return strBuf.toString();
	}

	public static String arrayToStr(byte[] allArray)
	{
		StringBuffer strBuf = new StringBuffer();
		for (byte value : allArray) {
			strBuf.append(" ").append(String.format("%02X", value));
		}
		return strBuf.toString();
	}

	/**
	 * 发送消息时，获取当前事件
	 *
	 * @return 当前时间
	 */
	public static String getFormatDate(String strDate) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long date = Long.valueOf(strDate)*1000;
		return format.format(new Date(date));
	}
	public static String getUUID() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}

	public static String getTime(int second) {
		if (second < 10) {
			return "00:0" + second;
		}
		if (second < 60) {
			return "00:" + second;
		}
		if (second < 3600) {
			int minute = second / 60;
			second = second - minute * 60;
			if (minute < 10) {
				if (second < 10) {
					return "0" + minute + ":0" + second;
				}
				return "0" + minute + ":" + second;
			}
			if (second < 10) {
				return minute + ":0" + second;
			}
			return minute + ":" + second;
		}
		int hour = second / 3600;
		int minute = (second - hour * 3600) / 60;
		second = second - hour * 3600 - minute * 60;
		if (hour < 10) {
			if (minute < 10) {
				if (second < 10) {
					return "0" + hour + ":0" + minute + ":0" + second;
				}
				return "0" + hour + ":0" + minute + ":" + second;
			}
			if (second < 10) {
				return "0" + hour + ":" + minute + ":0" + second;
			}
			return "0" + hour + ":" + minute + ":" + second;
		}
		if (minute < 10) {
			if (second < 10) {
				return hour + ":0" + minute + ":0" + second;
			}
			return hour + ":0" + minute + ":" + second;
		}
		if (second < 10) {
			return hour + ":" + minute + ":0" + second;
		}
		return hour + ":" + minute + ":" + second;
	}

	public static long getIntervalDate(String strDate) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date;
		try {
			date = format.parse(strDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			return 0;
		}
		return date.getTime() / 1000;
	}

	public static String unicode2String(String unicodeStr) {
		StringBuffer sb = new StringBuffer();
		String tmp = null;
		while(unicodeStr.length()>=4)
		{

			tmp = unicodeStr.substring(0, 4) ;
			unicodeStr = unicodeStr.substring(4, unicodeStr.length());
			char c = (char) Integer.parseInt(tmp, 16);
			sb.append(c);
		}


		return sb.toString();
	}

	public static String to16LenStr(String str)
	{
		byte[] baseArray = new byte[16];
		Arrays.fill(baseArray, (byte) '0');
		byte[] strArr = str.getBytes();
		System.arraycopy(strArr, 0, baseArray, 0, strArr.length);
		return new String(baseArray);
	}

	public static String getCellId(Context ctx) {
		TelephonyManager telephonyManager = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
		CellLocation cellLocation = telephonyManager.getCellLocation();
		String cellId = McIdInfo.Default_SaInfo;

		if (cellLocation == null) {
			Log.e("CID", "CellLocation is null");
			return "";
		}

		if (cellLocation instanceof GsmCellLocation) {
			// GSM 网络（移动/联通）
			GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
			int cid = gsmCellLocation.getCid();
			int lac = gsmCellLocation.getLac();
			cellId = "" + cid;
			Log.d("CID", "GSM CID: " + cid + ", LAC: " + lac);
		} else if (Build.VERSION.SDK_INT >= 29 && cellLocation instanceof CdmaCellLocation) {
			// CDMA 网络（电信，需 Android 10+）
			CdmaCellLocation cdmaCellLocation = (CdmaCellLocation) cellLocation;
			int bid = cdmaCellLocation.getBaseStationId();
			Log.d("CID", "CDMA BID: " + bid);
			cellId = "" + bid;
		} else {
			Log.e("CID", "Unsupported network type");
		}
		return cellId;
	}

//	public static final String Key_Num_Begin = "sip:";
//	public static final String Key_Num_IMPU = "@crsc.mcx.mnc020.mcc460.5gr";
//	public static final String Key_Num_IMPI = "@crsc.mcx.mnc020.mcc460.5gr";
//
//	public static final String Key_Num_McpttId = "@crsc.mcx.mnc020.mcc460.5gr";
//	public static final String Key_Num_McvideoId = "@crsc.mcx.mnc020.mcc460.5gr";
//	public static final String Key_Num_McdataId = "@crsc.mcx.mnc020.mcc460.5gr";


//	public static String toSipNum(String num,String endStr)
//	{
//		Log.i(THIS_FILE, "toSipNum num = " +num + " endStr = " + endStr);
//		StringBuffer strBuf = new StringBuffer(Key_Num_Begin);
//		strBuf.append(num);
//		strBuf.append(endStr);
//
//		Log.i(THIS_FILE, "toSipNum = " +strBuf.toString() );
//
//		return strBuf.toString();
//	}
//
//	public static String toImsSipNum(String num,String endStr)
//	{
//		Log.i(THIS_FILE, "toSipNum num = " +num + " endStr = " + endStr);
//		StringBuffer strBuf = new StringBuffer(Key_Num_Begin);
//		strBuf.append(num);
//		strBuf.append(endStr);
//
//		Log.i(THIS_FILE, "toSipNum = " +strBuf.toString() );
//
//		return strBuf.toString();
//	}

	public static String replaceHttpSvrAddr(String oldStr,String httpSvrAddr)
	{
		Log.debug(Common.class, "replaceHttpSvrAddr oldStr = " +oldStr + " httpSvrAddr = " + httpSvrAddr);
		oldStr = oldStr.replaceAll("^https?://[^/]+", "");
		Log.debug(Common.class, "replaceHttpSvrAddr oldStr = " +oldStr);
		return httpSvrAddr + oldStr;
	}


}
